package com.svs.framework.web;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baidu.ueditor.ActionEnter;
import com.svs.common.config.Global;

@Controller
public class UeditorController {

	@RequestMapping(value = "/ueditor/control")
	@ResponseBody
	public void ueditor(HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.setContentType("application/json");
		String rootPath = request.getSession().getServletContext().getRealPath("/");
		String exec = new ActionEnter(request, rootPath).exec();
		//处理保存成功的结果，将图片url前加上前缀
		JSONObject jsonObject = JSONObject.parseObject(exec);
		String url = jsonObject.getString("url");
		JSONArray jsonArray = (JSONArray)jsonObject.get("list");
		if(StringUtils.isNotBlank(url)){
			String str = Global.getContextPath() + url;
			jsonObject.put("url", StringUtils.replaceAll(str,"//", "/"));
			exec = jsonObject.toJSONString();
		}
		//如果是获取历史图片地址，则做对应的修改
		if(null!=jsonArray){
			for(int i = 0;i<jsonArray.size();i++){
				JSONObject obj = (JSONObject)jsonArray.get(i);
				String temUrl = obj.getString("url");
				if(StringUtils.isNotBlank(temUrl)){
					String str = Global.getContextPath() + temUrl;
					obj.put("url", StringUtils.replaceAll(str,"//", "/"));
				}
			}
			jsonObject.put("list", jsonArray);
			exec= jsonObject.toJSONString();
		}
		PrintWriter writer = response.getWriter();
		writer.write(exec);
		writer.flush();
		writer.close();

	}
}
